package cn.ios.hrm.exceptionhandle;

import cn.ios.hrm.util.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@RestControllerAdvice //aop的一种体现  相当于在controller有了切面
public class GlobalExceptionHandle {
    @ExceptionHandler(ArithmeticException.class)
    public AjaxResult mathException(ArithmeticException e){
        return AjaxResult.me().setSuccess(false).setMessage("算术异常信息："+e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public AjaxResult mathException(RuntimeException e){
        return AjaxResult.me().setSuccess(false).setMessage("异常信息："+e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodException(MethodArgumentNotValidException e){
        //获取参数效验未通过的字段
        BindingResult result = e.getBindingResult();
        //循环遍历拿到未通过的字段
        List<FieldError> errors = result.getFieldErrors();
        HashMap<String, Object> map = new HashMap<>();
        //拿到字段名字和错误信息
        errors.stream().forEach(error->{
            map.put(error.getField(),error.getDefaultMessage());
        });

        return AjaxResult.me().setSuccess(false).setMessage(map.toString()).setCode(HttpStatus.BAD_REQUEST.value());
    }

}
